package com.eliza.module.view.work.imageprocessing

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import com.eliza.module.view.work.db.Image
import com.eliza.module.view.work.db.TestDatabase
import java.util.Arrays


class WorkImageProcessingActivity : ComponentActivity() {

    companion object {
        private val IMAGE_REQUEST_CODE = 1
        private val TAG = "ImageProcessingActivity"

    }

    //    private val mImageRecyclerViewAdapter: ImageRecyclerViewAdapter = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            var asa by remember {
                mutableStateOf(emptyList<Image>())
            }
            TestDatabase.getInstance(this)
                .imageDao
                .imagesLiveData
                .observe(this) { images ->
                    asa = images
                }
            Text(text = "show")
            LazyColumn {
                items(asa) {
                    Text(text = it.mImage.toString())
                }
            }
        }
    }

    @Composable
    fun maix(modifier: Modifier = Modifier) {
        var btnx: @Composable (text: String, onClick: () -> Unit) -> Unit = { t, c ->
            Button(onClick = c) {
                Text(text = t)
            }
        }
        Column {
            btnx("add_image") {
                val chooseIntent = Intent(
                    Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                )
                chooseIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
                this@WorkImageProcessingActivity.startActivityForResult(
                    chooseIntent,
                    IMAGE_REQUEST_CODE
                )
            }
            btnx("clear_all") {
                WorkManager.getInstance(this@WorkImageProcessingActivity)
                    .enqueue(OneTimeWorkRequest.from(ImageCleanupWorker::class.java))
            }
        }
    }


    private val startActivityLauncher: ActivityResultLauncher<Intent> =
        registerForActivityResult(
            ActivityResultContracts.StartActivityForResult(),
        ) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                Log.d(TAG, "xxx: ")
            }
            val resultCode = result.resultCode
            val data = result.data!!
            var requestCode = 0
            if (requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data.getClipData() != null) {
                Log.d(TAG, "Image Selection Complete")
                val count: Int = data.clipData?.getItemCount() ?: 0
                val processingWork = arrayOfNulls<OneTimeWorkRequest>(count)
                val setupWork = arrayOfNulls<OneTimeWorkRequest>(count)
                for (i in 0 until count) {
                    val uriString: String = data.clipData?.getItemAt(i)?.getUri().toString() ?: ""
                    setupWork[i] = ImageSetupWorker.createWork(uriString)
                    processingWork[i] = ImageProcessingWorker.createWork(uriString)
                }
                WorkManager.getInstance(this@WorkImageProcessingActivity)
                    .beginWith(Arrays.asList<OneTimeWorkRequest>(*setupWork))
                    .then(Arrays.asList<OneTimeWorkRequest>(*processingWork))
                    .enqueue()
            } else if (requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data.getData() != null) {
                Log.d(TAG, "Image Selection Complete")
                val uriString: String = data.getData().toString()
                val setupWork = ImageSetupWorker.createWork(uriString)
                val processingWork = ImageProcessingWorker.createWork(uriString)
                WorkManager.getInstance(this@WorkImageProcessingActivity)
                    .beginWith(setupWork)
                    .then(processingWork)
                    .enqueue()
            } else if (requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_CANCELED) {
                Log.d(TAG, "Image Selection Cancelled")
            } else {
                throw UnsupportedOperationException()
            }
        }
}